package com.chenliang.autetest.service.impl;

import org.apache.jmeter.protocol.jdbc.config.DataSourceElementBeanInfo;
import org.apache.jmeter.save.SaveService;

import java.io.IOException;

import com.chenliang.autetest.listener.InvokeResultCollector;
import com.chenliang.autetest.service.CallService;
import org.apache.jmeter.control.LoopController;
import org.apache.jmeter.control.gui.LoopControlPanel;
import org.apache.jmeter.engine.StandardJMeterEngine;
import org.apache.jmeter.protocol.http.control.Header;
import org.apache.jmeter.protocol.http.control.HeaderManager;
import org.apache.jmeter.protocol.jdbc.AbstractJDBCTestElement;
import org.apache.jmeter.protocol.jdbc.config.DataSourceElement;
import org.apache.jmeter.protocol.jdbc.sampler.JDBCSampler;
import org.apache.jmeter.reporters.ResultCollector;
import org.apache.jmeter.reporters.Summariser;
import org.apache.jmeter.samplers.SampleResult;
import org.apache.jmeter.samplers.SampleSaveConfiguration;
import org.apache.jmeter.testelement.TestElement;
import org.apache.jmeter.testelement.TestPlan;
import org.apache.jmeter.testelement.property.*;
import org.apache.jmeter.threads.ThreadGroup;
import org.apache.jmeter.threads.gui.ThreadGroupGui;
import org.apache.jmeter.util.JMeterUtils;
import org.apache.jorphan.collections.HashTree;
import org.apache.jorphan.collections.ListedHashTree;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.sql.Connection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

/**
 * @program: auto_test
 * @description:
 * @author: chenLiang
 * @create: 2022-12-12 20:25
 */
@Service
public class CallServiceImpl implements CallService {



    @Override
    public void call() {
        // 加载jmeter
        File jmeterHome = new File("D:\\app\\apache-jmeter-5.5");

        String slash = System.getProperty("file.separator");

        if (jmeterHome.exists()) {

            File jmeterProperties = new File(jmeterHome.getPath() + slash + "bin" + slash + "jmeter.properties");

            if (jmeterProperties.exists()) {

                //JMeter Engine
                StandardJMeterEngine jmeter = new StandardJMeterEngine();

                //JMeter initialization (properties, log levels, locale, etc)
                String homePath = jmeterHome.getPath();
                JMeterUtils.setJMeterHome(homePath);

                String propertiesPath = jmeterProperties.getPath();
                JMeterUtils.loadJMeterProperties(propertiesPath);

                JMeterUtils.initLogging();// you can comment this line out to see extra log messages of i.e. DEBUG level
                JMeterUtils.initLocale();

                HashTree hashTree = getHashTreeByJdbc();
               // HashTree hashTree =getHashTreeByJdbcToUtil();


                Summariser summer = null;
                String summariserName = JMeterUtils.getPropDefault("summariser.name", "summary");
                if (summariserName.length() > 0) {
                    summer = new Summariser(summariserName);
                }


                String logFile = "D:\\temp\\report\\report.jtl";
                ResultCollector resultCollector = new InvokeResultCollector(summer);
                resultCollector.setFilename(logFile);
                hashTree.add(hashTree.getArray(), resultCollector);

                // Run Test Plan
                jmeter.configure(hashTree);

                jmeter.run();


            }
        }


    }

    private static HashTree getHashTreeByJdbcToUtil() {

        HashTree hashTree = null;
        try {
            hashTree = SaveService.loadTree(new File("D:\\Desktop\\最新测试.jmx"));
        } catch (IOException e) {
            e.printStackTrace();
        }

        return hashTree;
    }

    /**
     * 封装树结构
     *
     * @return
     */
    private HashTree getHashTreeByJdbc() {

        /**
         * add 添加同级
         * put 添加子集
         */

        // 构建顶级执行树
        HashTree topTree = new HashTree();

        // 添加执行计划
        TestPlan plan = new TestPlan();

        // 处理sql查询
        HashTree sqlQueryTree = new ListedHashTree();

        DataSourceElement jdbcConnectionConfiguration = getJdbcConnectionConfiguration();

        sqlQueryTree.put(jdbcConnectionConfiguration, new ListedHashTree());

        // 构建循环控制器.循环次数1
        LoopController loopController = getLoopController();

        // 构建线程组对象
        ThreadGroup threadGroup = getThreadGroup(loopController);

        HashTree sql = new ListedHashTree();

        JDBCSampler jdbcSampler = createJdbcSampler();

        sql.add(jdbcSampler);

        sqlQueryTree.put(threadGroup, sql);

        topTree.put(plan, sqlQueryTree);

        return topTree;

    }

    @NotNull
    private JDBCSampler createJdbcSampler() {
        JDBCSampler jdbcSampler = new JDBCSampler();
        jdbcSampler.setResultSetMaxRows("20");
        jdbcSampler.setResultVariable("result");
        String timeStr = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        jdbcSampler.setProperty("TestElement.name", "测试sql查询" + timeStr);
        jdbcSampler.setProperty("dataSource", "chenliang");
        jdbcSampler.setProperty("queryType", "Select Statement");
        jdbcSampler.setProperty("query", "select  *   from core_user where name='陈亮'");
        jdbcSampler.setProperty("resultSetHandler", "Store as String");
        return jdbcSampler;
    }

    public static HeaderManager createHeaderManager() {
        HeaderManager headerManager = new HeaderManager();
        ArrayList<TestElementProperty> list2 = new ArrayList<>();
        Header header = new Header();
        header.setProperty(new StringProperty("Header.name", "Content-Type"));
        header.setProperty(new StringProperty("Header.value", "application/json"));
        TestElementProperty HeaderElement = new TestElementProperty("", header);
        list2.add(HeaderElement);
        headerManager.setProperty(new CollectionProperty("HeaderManager.headers", list2));
        headerManager.setProperty(new StringProperty("TestElement.test_class",
                "org.apache.jmeter.protocol.http.control.HeaderManager"));
        headerManager.setProperty(new StringProperty("TestElement.name", "HTTP Header Manager"));
        headerManager.setProperty(new StringProperty("TestElement.enabled", "true"));
        headerManager.setProperty(new StringProperty("TestElement.gui_class",
                "org.apache.jmeter.protocol.http.gui.HeaderPanel"));
        return headerManager;
    }

    public ResultCollector createResultCollector() {

        ResultCollector resultCollector = new ResultCollector();
        resultCollector.setProperty(new BooleanProperty("ResultCollector.error_logging", false));
        resultCollector.setProperty(new ObjectProperty("saveConfig", createSampleSaveConfiguration()));
        resultCollector.setProperty(new StringProperty("TestElement.gui_class",
                "org.apache.jmeter.visualizers.ViewResultsFullVisualizer"));
        resultCollector.setProperty(new StringProperty("TestElement.name", "View Results Tree"));
        resultCollector.setProperty(new StringProperty("TestElement.enabled", "true"));
        resultCollector.setProperty(new StringProperty("filename", ""));
        return resultCollector;
    }


    /**
     * 构建数据库连接元素对象
     *
     * @return
     */
    private DataSourceElement getJdbcConnectionConfiguration() {
        DataSourceElement config = new DataSourceElement();
//        config.setConnectionAge("5000");
//        config.setDataSource("chenliang");
//        config.setDbUrl("jdbc:mysql://47.103.182.43:3306/chenliang_service");
//        config.setDriver("com.mysql.cj.jdbc.Driver");
//        config.setPassword("Ggzy1314");
//        config.setPoolMax("0");
//        config.setTimeout("10000");
//        config.setTrimInterval("60000");
//        config.setUsername("ggzy");
//        config.setAutocommit(true);
//        config.setPreinit(false);
//        config.setKeepAlive(true);
//        config.setTransactionIsolation("DEFAULT");
//        config.setInitQuery("select  *   from core_user");
//        config.setEnabled(true);

 //       DataSourceElementBeanInfo dataSourceElementBeanInfo = new DataSourceElementBeanInfo();


        config.setProperty("TestPlan.comments", "配置");
        config.setProperty("dataSource", "chenliang");
        config.setProperty("poolMax", "0");
        config.setProperty("timeout", 10000);
        config.setProperty("trimInterval", 60000);
        config.setProperty("autocommit", true);
        config.setProperty("transactionIsolation", "DEFAULT");
        config.setProperty("preinit", false);
        config.setProperty("initQuery", "select  *   from core_user");
        config.setProperty("keepAlive", true);
        config.setProperty("connectionAge", 5000);
        config.setProperty("dbUrl", "jdbc:mysql://47.103.182.43:3306/chenliang_service");
        config.setProperty("driver", "com.mysql.cj.jdbc.Driver");
        config.setProperty("username", "ggzy");
        config.setProperty("password", "Ggzy1314");
        config.setEnabled(true);
        return config;
    }

    /**
     * 构建线程组对象
     *
     * @param loopController
     * @return
     */
    private static ThreadGroup getThreadGroup(LoopController loopController) {
        ThreadGroup threadGroup = new ThreadGroup();
        threadGroup.setName("Sample Thread Group");
        threadGroup.setNumThreads(1);
        threadGroup.setRampUp(1);
        threadGroup.setSamplerController(loopController);
        threadGroup.setProperty(TestElement.TEST_CLASS, ThreadGroup.class.getName());
        threadGroup.setProperty(TestElement.GUI_CLASS, ThreadGroupGui.class.getName());
        return threadGroup;
    }


    /**
     * 构建循环控制器对象
     *
     * @return
     */
    private static LoopController getLoopController() {
        LoopController loopController = new LoopController();
        loopController.setLoops(1);// 调用次数
        loopController.setFirst(true);
        loopController.setProperty(TestElement.TEST_CLASS, LoopController.class.getName());
        loopController.setProperty(TestElement.GUI_CLASS, LoopControlPanel.class.getName());
        loopController.initialize();
        return loopController;
    }


    /**
     * 构建查看结果树对象
     *
     * @return
     */
    public SampleSaveConfiguration createSampleSaveConfiguration() {
        SampleSaveConfiguration sampleSaveConfiguration = new SampleSaveConfiguration();
        sampleSaveConfiguration.setTime(true);
        sampleSaveConfiguration.setLatency(true);
        sampleSaveConfiguration.setTimestamp(true);
        sampleSaveConfiguration.setSuccess(true);
        sampleSaveConfiguration.setLabel(true);
        sampleSaveConfiguration.setCode(true);
        sampleSaveConfiguration.setMessage(true);
        sampleSaveConfiguration.setThreadName(true);
        sampleSaveConfiguration.setDataType(true);
        sampleSaveConfiguration.setEncoding(false);
        sampleSaveConfiguration.setAssertions(true);
        sampleSaveConfiguration.setSubresults(true);
        sampleSaveConfiguration.setResponseData(false);
        sampleSaveConfiguration.setSamplerData(false);
        sampleSaveConfiguration.setAsXml(false);
        sampleSaveConfiguration.setFieldNames(true);
        sampleSaveConfiguration.setResponseHeaders(false);
        sampleSaveConfiguration.setRequestHeaders(false);
        sampleSaveConfiguration.setAssertionResultsFailureMessage(true);
        sampleSaveConfiguration.setBytes(true);
        sampleSaveConfiguration.setSentBytes(true);
        sampleSaveConfiguration.setUrl(true);
        sampleSaveConfiguration.setThreadCounts(true);
        sampleSaveConfiguration.setIdleTime(true);
        sampleSaveConfiguration.setConnectTime(true);
        return sampleSaveConfiguration;
    }

    @Override
    public void call2() {

        JDBCSampler jdbcSampler = new JDBCSampler();
//        jdbcSampler.setResultSetMaxRows("20");
//        jdbcSampler.setResultVariable("result");
//        String timeStr = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
//        jdbcSampler.setProperty("TestElement.name", "测试sql查询" + timeStr);
//        jdbcSampler.setProperty("dataSource", "chenliang");
//        jdbcSampler.setProperty("queryType", "Select Statement");
//        jdbcSampler.setProperty("query", "select  *   from core_user");
//        jdbcSampler.setProperty("resultSetHandler", "Store as String");
//
//
//        jdbcSampler.
    }
}
